package com.uzai.console.service.tb.tbridpid.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScAdzoneCreateRequest;
import com.taobao.api.request.TbkScInvitecodeGetRequest;
import com.taobao.api.request.TbkScPublisherInfoSaveRequest;
import com.taobao.api.response.TbkScAdzoneCreateResponse;
import com.taobao.api.response.TbkScInvitecodeGetResponse;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.enums.LogBizTypeEnum;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.entity.TbRidPid;
import com.uzai.console.entity.TbRidToken;
import com.uzai.console.entity.TbToken;
import com.uzai.console.mapper.TbRidPidMapper;
import com.uzai.console.mapper.TbRidTokenMapper;
import com.uzai.console.mapper.TbTokenMapper;
import com.uzai.console.service.tb.tbridpid.TbRidPidService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月13日 11:33
 */
@Service
public class TbRidPidServiceImpl implements TbRidPidService {

    Logger logger = LoggerFactory.getLogger(TbRidPidServiceImpl.class);

    @Autowired
    private TbRidPidMapper tbRidPidMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private TbRidTokenMapper tbRidTokenMapper;

    @Value("${tb.api.url}")
    private String tbApiUrl;
    @Value("${tb.token.appkey}")
    private String appkey;
    @Value("${tb.token.appsecret}")
    private String appsecret;

    /**
     * 添加饿了么买家身份token之后，自动添加其他饿了么token的pid和rid关系表
     * 目前查询数量过大，会占用太大内存，故暂时不用此方法，如果需要此方法，需改成分页查询
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbTokenDto_rid
     * @return null
     */
    @Async("taskExecutor")
    public void addTbRidPidByTokenAdd(TbRidToken tbTokenDto_rid){
        //查询rid个数未满300个的饿了么token
        List<TbToken> tbTokenList = tbRidPidMapper.selectTbTokenListByRidLessThan300();
        if(tbTokenList != null && tbTokenList.size() > 0){
            TaobaoClient client = new DefaultTaobaoClient(tbApiUrl, appkey, appsecret);
            for (TbToken tbToken_inviterCode : tbTokenList){
                if(tbToken_inviterCode.getId().longValue() != tbTokenDto_rid.getId().longValue()){ //验证是不是自己，如果是自己则不处理
                    //获取该授权的邀请码
                    String inviterCode =  getInvitecode(client, tbToken_inviterCode);
                    if(StringUtils.isNotBlank(inviterCode)){
                        addTbRidPid(client, inviterCode, tbToken_inviterCode, tbTokenDto_rid);
                    }
                }
            }
        }
    }

    /**
     * 获取渠道-pid列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbToken_inviterCode
     * @return null
     */
    @Async("taskExecutor")
    public void authRelationId(TbToken tbToken_inviterCode){

        //删除旧的rid-pid关系
        tbRidPidMapper.deleteByTbTokenId(tbToken_inviterCode.getId());
        
        //从联盟中查询出300个授权未到期的token出来
        List<TbRidToken> tbRidTokenList =  tbRidTokenMapper.selectTbRidTokenListEqual300(tbToken_inviterCode.getId());
        if(tbRidTokenList != null && tbRidTokenList.size() > 0){
            TaobaoClient client = new DefaultTaobaoClient(tbApiUrl, appkey, appsecret);
            //获取该授权的邀请码
            String inviterCode =  getInvitecode(client, tbToken_inviterCode);
            if(StringUtils.isNotBlank(inviterCode)){
                for (TbRidToken tbRidToken_rid : tbRidTokenList){
                    if(tbToken_inviterCode.getId().longValue() != tbRidToken_rid.getId().longValue()) { //验证是不是自己，如果是自己则不处理
                        addTbRidPid(client, inviterCode, tbToken_inviterCode, tbRidToken_rid);
                    }
                }
            }
        }
    }

    /**
     * 获取该授权的邀请码
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbTokenDto_inviterCode   --生成邀请码的token,即插入rid-pid的token
     * @return String
     */
    private String getInvitecode(TaobaoClient client, TbToken tbTokenDto_inviterCode){
        //获取邀请码-淘宝邀请码生成-http://gw.api.taobao.com/router/rest
        String inviterCode = "";
        TbkScInvitecodeGetRequest req_inviterCode = new TbkScInvitecodeGetRequest();
        //req_inviterCode.setRelationId(11L);
        req_inviterCode.setRelationApp("common");
        req_inviterCode.setCodeType(1L);
        try {
            TbkScInvitecodeGetResponse rsp_inviterCode = client.execute(req_inviterCode, tbTokenDto_inviterCode.getAccessToken());
            if (rsp_inviterCode != null) {
                TbkScInvitecodeGetResponse.Data data_inviterCode = rsp_inviterCode.getData();
                //邀请码为空，则保存运行日志
                if(data_inviterCode == null || StringUtils.isBlank(data_inviterCode.getInviterCode())){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_ELM_TOKEN_VALUE,
                            tbTokenDto_inviterCode.getMerId(), 0, null,
                            "",0L,
                            tbTokenDto_inviterCode.getUserName()+":"+rsp_inviterCode.getSubMsg())));
                    return inviterCode;
                }else{
                    inviterCode =  data_inviterCode.getInviterCode();
                    return inviterCode;
                }
            }
        }catch (Exception e){
            logger.error("----pid-rid-关系增加失败---error={}",e.getMessage());
            return inviterCode;
        }

        return inviterCode;
    }

    /**
     * 添加饿了么token之后，自动添加其他饿了么token的pid和rid关系表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbTokenDto_inviterCode   --生成邀请码的token
     * @param inviterCode              --生成邀请码,即插入rid-pid的token
     * @param tbRidTokenDto_rid        --通过生成的邀请码，与这个tkoen,请求生成渠道id
     * @return null
     */
    private void addTbRidPid(TaobaoClient client, String inviterCode, TbToken tbTokenDto_inviterCode, TbRidToken tbRidTokenDto_rid){
        try {
            //获取渠道id
            if(StringUtils.isNotBlank(inviterCode)){ //邀请码不为空
                //获取渠道id
                TbkScPublisherInfoSaveRequest req_rid = new TbkScPublisherInfoSaveRequest();
                req_rid.setInviterCode(inviterCode);
                req_rid.setInfoType(1L);
                TbkScPublisherInfoSaveResponse rsp_rid = client.execute(req_rid, tbRidTokenDto_rid.getAccessToken());
                if(rsp_rid != null){
                    TbkScPublisherInfoSaveResponse.Data data_rid = rsp_rid.getData();
                    if(data_rid != null){
                        Long relationId = data_rid.getRelationId();
                        if(relationId == null){
                            logger.error("----获取渠道id失败---error={}", rsp_rid.getBody());
                            return;
                        }
                        if(relationId != null){
                            //插入pid-rid关系表中
                            List<String> elmPidList = JSONObject.parseArray(tbTokenDto_inviterCode.getElmPids(), String.class);
                            if(elmPidList != null && elmPidList.size() > 0){
                                Integer now = DateUtil.getNowTime();
                                for (String elmPid : elmPidList){
                                    TbRidPid tbRidPid = tbRidPidMapper.selectByRalationIdAndPid(String.valueOf(relationId), elmPid);
                                    if(tbRidPid == null){ //不存在，才能插入
                                        tbRidPid = new TbRidPid();
                                        tbRidPid.setId(IdWorker.getId());
                                        tbRidPid.setMerId(tbTokenDto_inviterCode.getMerId());
                                        tbRidPid.setTbTokenId(tbTokenDto_inviterCode.getId());
                                        tbRidPid.setTbTokenUserId(tbTokenDto_inviterCode.getUserId());
                                        tbRidPid.setRelationId(String.valueOf(relationId));
                                        tbRidPid.setPid(elmPid);
                                        tbRidPid.setCreateTime(now);
                                        tbRidPid.setUpdateTime(now);
                                        tbRidPidMapper.insertSelective(tbRidPid);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("----pid-rid-关系增加失败---error={}",e.getMessage());
        }
    }

    /**
     * 提供淘宝客创建广告位
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param client       --淘宝客户端
     * @param sessionKey   --联盟token
     * @param siteId       --网站ID
     * @param adzoneName   --广告位名称，最大长度64字符
     * @return String
     */
    public String createPid(TaobaoClient client, String sessionKey,  Long siteId, String adzoneName){
        //提供淘宝客创建广告位-https://open.taobao.com/api.htm?docId=34751&docType=2
        TbkScAdzoneCreateRequest req = new TbkScAdzoneCreateRequest();
        req.setSiteId(siteId);
        req.setAdzoneName(adzoneName);

        try {
            TbkScAdzoneCreateResponse rsp = client.execute(req, sessionKey);
            if (rsp != null) {
                TbkScAdzoneCreateResponse.MapData mapData = rsp.getData();
                if(mapData != null){
                    return mapData.getModel();
                }
            }
        }catch (Exception e){
            logger.error("--createPid--error={}",e.getMessage());
            return null;
        }
        return null;
    }


}
